<template>
  <div class="team-page">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="title">项目团队管理</span>
            <el-tag type="info" style="margin-left: 10px">
              共 {{ projects.length }} 个项目
            </el-tag>
          </div>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索项目或成员"
              clearable
              style="width: 250px; margin-right: 10px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              添加成员
            </el-button>
          </div>
        </div>
      </template>

      <!-- 左右分栏布局 -->
      <div class="team-content">
        <!-- 左侧：项目列表 -->
        <div class="project-list-panel">
          <div class="panel-header">
            <span class="panel-title">项目列表</span>
          </div>
          <div class="project-items">
            <div
              v-for="project in filteredProjects"
              :key="project.id"
              class="project-item"
              :class="{ active: selectedProjectId === project.id }"
              @click="handleSelectProject(project.id)"
            >
              <div class="project-item-content">
                <div class="project-item-header">
                  <span class="project-name">{{ project.name }}</span>
                  <el-badge :value="getProjectMemberCount(project.id)" type="primary" />
                </div>
                <div class="project-item-footer">
                  <el-tag size="small" :type="getStatusType(project.status)">
                    {{ getStatusLabel(project.status) }}
                  </el-tag>
                  <el-text size="small" type="info">{{ project.owner }}</el-text>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：成员详情 -->
        <div class="member-detail-panel">
          <div v-if="selectedProjectId" class="member-content">
            <div class="panel-header">
              <div class="panel-title-group">
                <span class="panel-title">{{ currentProject?.name }}</span>
                <el-tag type="primary" size="small" style="margin-left: 10px">
                  {{ members.length }} 名成员
                </el-tag>
              </div>
              <el-button size="small" type="primary" @click="handleAdd">
                <el-icon><Plus /></el-icon>
                添加成员
              </el-button>
            </div>

            <!-- 成员表格 -->
            <el-table :data="members" border v-loading="loading" style="margin-top: 15px">
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column label="成员" width="200">
                <template #default="{ row }">
                  <div class="member-cell">
                    <el-avatar :size="40" :style="{ background: getAvatarColor(row.name) }">
                      {{ row.name.substring(0, 2) }}
                    </el-avatar>
                    <div class="member-info-inline">
                      <div class="member-name">{{ row.name }}</div>
                      <div class="member-dept">{{ row.department }}</div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="role" label="项目角色" width="150">
                <template #default="{ row }">
                  <el-tag type="primary" size="small">{{ row.role }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="任务统计" width="150">
                <template #default="{ row }">
                  <div class="task-stats-inline">
                    <span>负责 {{ row.taskCount }}</span>
                    <el-divider direction="vertical" />
                    <span>完成 {{ row.completedTasks }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="完成率" width="150">
                <template #default="{ row }">
                  <el-progress
                    :percentage="row.taskCount > 0 ? Math.round((row.completedTasks / row.taskCount) * 100) : 0"
                    :color="getProgressColor(row.taskCount > 0 ? (row.completedTasks / row.taskCount) * 100 : 0)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="{ row }">
                  <el-button link type="primary" size="small" @click="handleViewTasks(row)">
                    查看任务
                  </el-button>
                  <el-button link type="danger" size="small" @click="handleRemove(row)">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 未选择项目的提示 -->
          <el-empty
            v-else
            description="请从左侧选择项目查看团队成员"
            :image-size="150"
          />
        </div>
      </div>
    </el-card>

    <!-- 添加成员对话框 -->
    <el-dialog v-model="dialogVisible" title="添加团队成员" width="600px">
      <el-alert
        title="从员工列表中选择成员加入项目团队"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      />
      
      <el-form :model="form" label-width="100px">
        <el-form-item label="选择成员">
          <el-select 
            v-model="form.userId" 
            placeholder="请选择员工"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="user in availableUsers"
              :key="user.id"
              :label="`${user.name} - ${user.department} - ${user.position}`"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="项目角色">
          <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="项目经理" value="项目经理" />
            <el-option label="技术负责人" value="技术负责人" />
            <el-option label="前端工程师" value="前端工程师" />
            <el-option label="后端工程师" value="后端工程师" />
            <el-option label="UI设计师" value="UI设计师" />
            <el-option label="测试工程师" value="测试工程师" />
            <el-option label="产品经理" value="产品经理" />
            <el-option label="运维工程师" value="运维工程师" />
          </el-select>
        </el-form-item>

        <el-form-item label="权限设置">
          <el-checkbox-group v-model="form.permissions">
            <el-checkbox value="task_manage">任务管理</el-checkbox>
            <el-checkbox value="member_manage">成员管理</el-checkbox>
            <el-checkbox value="file_manage">文件管理</el-checkbox>
            <el-checkbox value="setting_manage">项目设置</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
import { Plus, Search } from '@element-plus/icons-vue'

const route = useRoute()
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const selectedProjectId = ref(null)
const searchKeyword = ref('')

// 表单数据
const form = reactive({
  userId: null,
  role: '',
  permissions: []
})

// 项目列表
const projects = ref([
  { id: 1, name: 'ERP系统开发', status: 'active', owner: '张三' },
  { id: 2, name: '商城小程序', status: 'active', owner: '李四' },
  { id: 3, name: 'CRM系统升级', status: 'completed', owner: '王五' },
  { id: 4, name: '数据分析平台', status: 'active', owner: '张三' },
  { id: 5, name: '移动APP开发', status: 'active', owner: '赵六' },
  { id: 6, name: '智能仓储系统', status: 'active', owner: '钱七' },
  { id: 7, name: '在线教育平台', status: 'active', owner: '孙八' },
  { id: 8, name: '供应链管理', status: 'paused', owner: '周九' }
])

// 搜索过滤后的项目
const filteredProjects = computed(() => {
  if (!searchKeyword.value) {
    return projects.value
  }
  const keyword = searchKeyword.value.toLowerCase()
  return projects.value.filter(project => {
    // 搜索项目名称
    if (project.name.toLowerCase().includes(keyword)) {
      return true
    }
    // 搜索项目成员
    const members = projectMembers.value[project.id] || []
    return members.some(member => member.name.toLowerCase().includes(keyword))
  })
})

// 当前项目
const currentProject = computed(() => {
  return projects.value.find(p => p.id === selectedProjectId.value)
})

// 所有员工列表
const allUsers = ref([
  { id: 1, name: '张三', department: '研发部', position: '高级工程师' },
  { id: 2, name: '李四', department: '研发部', position: '前端工程师' },
  { id: 3, name: '王五', department: '研发部', position: '后端工程师' },
  { id: 4, name: '赵六', department: '测试部', position: '测试工程师' },
  { id: 5, name: '钱七', department: '产品部', position: '产品经理' },
  { id: 6, name: '孙八', department: '设计部', position: 'UI设计师' },
  { id: 7, name: '周九', department: '研发部', position: '运维工程师' },
  { id: 8, name: '吴十', department: '研发部', position: '架构师' }
])

// 项目成员数据（每个项目的成员）
const projectMembers = ref({
  1: [
    { id: 1, userId: 1, name: '张三', role: '项目经理', department: '研发部', taskCount: 8, completedTasks: 5 },
    { id: 2, userId: 2, name: '李四', role: '前端工程师', department: '研发部', taskCount: 12, completedTasks: 8 },
    { id: 3, userId: 3, name: '王五', role: '后端工程师', department: '研发部', taskCount: 10, completedTasks: 6 },
    { id: 4, userId: 4, name: '赵六', role: '测试工程师', department: '测试部', taskCount: 6, completedTasks: 4 }
  ],
  2: [
    { id: 5, userId: 2, name: '李四', role: '技术负责人', department: '研发部', taskCount: 15, completedTasks: 10 },
    { id: 6, userId: 6, name: '孙八', role: 'UI设计师', department: '设计部', taskCount: 8, completedTasks: 6 }
  ],
  3: [
    { id: 7, userId: 3, name: '王五', role: '项目经理', department: '研发部', taskCount: 12, completedTasks: 9 },
    { id: 8, userId: 4, name: '赵六', role: '测试工程师', department: '测试部', taskCount: 7, completedTasks: 5 }
  ],
  4: [
    { id: 9, userId: 1, name: '张三', role: '技术负责人', department: '研发部', taskCount: 10, completedTasks: 7 }
  ],
  5: [],
  6: [
    { id: 10, userId: 7, name: '周九', role: '运维工程师', department: '研发部', taskCount: 5, completedTasks: 3 }
  ],
  7: [
    { id: 11, userId: 5, name: '钱七', role: '产品经理', department: '产品部', taskCount: 9, completedTasks: 6 },
    { id: 12, userId: 6, name: '孙八', role: 'UI设计师', department: '设计部', taskCount: 7, completedTasks: 5 }
  ],
  8: []
})

// 当前项目的成员
const members = computed(() => {
  return projectMembers.value[selectedProjectId.value] || []
})

// 可用的员工（排除已加入的）
const availableUsers = computed(() => {
  const memberUserIds = members.value.map(m => m.userId)
  return allUsers.value.filter(user => !memberUserIds.includes(user.id))
})

// 获取项目成员数量
const getProjectMemberCount = (projectId) => {
  return projectMembers.value[projectId]?.length || 0
}

// 状态类型
const getStatusType = (status) => {
  const types = { active: 'primary', completed: 'success', paused: 'warning' }
  return types[status] || ''
}

// 状态文本
const getStatusLabel = (status) => {
  const labels = { active: '进行中', completed: '已完成', paused: '已暂停' }
  return labels[status] || status
}

// 头像颜色
const getAvatarColor = (name) => {
  const colors = ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399', '#c71585', '#ff6347', '#4169e1']
  const hash = name.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
  return colors[hash % colors.length]
}

// 进度颜色
const getProgressColor = (percentage) => {
  if (percentage < 30) return '#f56c6c'
  if (percentage < 70) return '#e6a23c'
  return '#67c23a'
}

// 选择项目
const handleSelectProject = (projectId) => {
  selectedProjectId.value = projectId
}

// 添加成员
const handleAdd = () => {
  if (!selectedProjectId.value) {
    ElMessage.warning('请先选择项目')
    return
  }
  
  if (availableUsers.value.length === 0) {
    ElMessage.warning('没有可添加的员工了')
    return
  }
  
  form.userId = null
  form.role = ''
  form.permissions = []
  dialogVisible.value = true
}

// 提交添加
const handleSubmit = () => {
  if (!form.userId) {
    ElMessage.warning('请选择员工')
    return
  }
  if (!form.role) {
    ElMessage.warning('请选择项目角色')
    return
  }
  
  submitLoading.value = true
  
  setTimeout(() => {
    const user = allUsers.value.find(u => u.id === form.userId)
    if (user) {
      const newMember = {
        id: Date.now(),
        userId: user.id,
        name: user.name,
        role: form.role,
        department: user.department,
        taskCount: 0,
        completedTasks: 0,
        permissions: form.permissions
      }
      
      if (!projectMembers.value[selectedProjectId.value]) {
        projectMembers.value[selectedProjectId.value] = []
      }
      projectMembers.value[selectedProjectId.value].push(newMember)
      
      ElMessage.success('添加成员成功')
      dialogVisible.value = false
    }
    submitLoading.value = false
  }, 500)
}

// 查看任务
const handleViewTasks = (member) => {
  ElMessage.info(`查看 ${member.name} 的任务`)
}

// 移除成员
const handleRemove = (member) => {
  ElMessageBox.confirm(`确定将 ${member.name} 移出项目团队吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    const members = projectMembers.value[selectedProjectId.value]
    const index = members.findIndex(m => m.id === member.id)
    if (index > -1) {
      members.splice(index, 1)
      ElMessage.success('移除成功')
    }
  }).catch(() => {})
}

// 初始化
onMounted(() => {
  // 从路由参数或默认选择第一个项目
  const projectId = route.query.projectId ? parseInt(route.query.projectId) : projects.value[0]?.id
  if (projectId) {
    selectedProjectId.value = projectId
  }
})
</script>

<style scoped>
.team-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

/* 左右分栏布局 */
.team-content {
  display: flex;
  gap: 20px;
  min-height: 600px;
}

/* 左侧项目列表 */
.project-list-panel {
  width: 320px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  overflow: hidden;
}

.panel-header {
  padding: 15px 20px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.panel-title-group {
  display: flex;
  align-items: center;
}

.project-items {
  max-height: 600px;
  overflow-y: auto;
}

.project-item {
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.3s;
  border-bottom: 1px solid #f0f0f0;
}

.project-item:hover {
  background: #f5f7fa;
}

.project-item.active {
  background: #ecf5ff;
  border-left: 3px solid #409eff;
}

.project-item-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.project-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.project-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.project-item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 右侧成员详情 */
.member-detail-panel {
  flex: 1;
  background: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  padding: 15px 20px;
}

.member-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 成员单元格 */
.member-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.member-info-inline {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.member-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.member-dept {
  font-size: 12px;
  color: #909399;
}

.task-stats-inline {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #606266;
}
</style>

